<template>
  <div class="task-list-container">
    <CPageTable @register="registerPage" v-model:search-form="searchForm">
      <template #headerRightButton>
        <el-button type="primary" @click="handleAddTask" v-btnPermission="'ECI_INVENTORY_TASK_ADD'">
          <CIcon class="g-mr4" type="c-xian-xinjian"></CIcon>
          创建核算任务
        </el-button>
      </template>
      <template #organizationNameSlot="{ scope }">
        <CTableColumn
          :main-text="scope.row.organizationName"
          :sub-text="scope.row.taskNo"
          :is-link="hasBtnPermission('ECI_INVENTORY_TASK_VIEW')"
          @link-click="handleAccounting(scope.row)"
        ></CTableColumn>
      </template>
      <template #creatorSlot="{ scope }">
        <CTableColumn
          :main-text="scope.row.creator"
          :sub-text="scope.row.createTime"
        ></CTableColumn>
      </template>
      <template #accountProgressHeaderSlot>
        <div class="g-flex-center-center">
          <span>核算进度</span>
          <el-tooltip content="已核算组织数/需核算组织总数" placement="top">
            <CIcon
              class="g-ml4 g-cur-poi inventory-task-list-table-icon"
              type="c-xian-shuoming"
            ></CIcon>
          </el-tooltip>
        </div>
      </template>
      <template #accountProgressSlot="{ scope }">
        {{ `${empty(scope.row.accountedNum)} / ${empty(scope.row.totalNum)}` }}
      </template>
      <template #accountStatusSlot="{ scope }">
        <el-tag
          class="g-tag"
          hit
          type="success"
          v-if="scope.row.totalNum && scope.row.totalNum === scope.row.accountedNum"
          >{{ InventoryTaskListAccountStatusMap.ACCOUNTED }}</el-tag
        >
        <el-tag
          class="g-tag"
          hit
          type="default"
          v-else-if="
            scope.row.totalNum &&
            scope.row.accountedNum &&
            scope.row.totalNum > scope.row.accountedNum
          "
          >{{ InventoryTaskListAccountStatusMap.ACCOUNTING }}</el-tag
        >
        <el-tag class="g-tag" hit type="info" v-else-if="!scope.row.accountedNum">{{
          InventoryTaskListAccountStatusMap.NOT_ACCOUNT
        }}</el-tag>
      </template>
      <template #op="{ scope }">
        <CTableButtonGroup :buttons-config="getTableButtonsConfig(scope.row)" :showMoreNum="3" />
      </template>
    </CPageTable>
    <AddOrEditTaskDialog
      v-model:visible="addOrEditTaskVisible"
      :taskNo="addOrEditTaskTaskNo"
      :type="addOrEditTaskType"
      @refresh="refresh"
    ></AddOrEditTaskDialog>
  </div>
</template>
<script lang="ts">
export default {
  name: 'InventoryTaskList'
};
</script>
<script lang="ts" setup>
import { ref, reactive } from 'vue';
import type { GetTaskListResult } from '@/apis/eci/emissionAccounting/model/inventoryTaskModel';
import { postDeleteTask } from '@/apis/eci/emissionAccounting/inventoryTask';
import AddOrEditTaskDialog from './components/AddOrEditTaskDialog/index.vue';
import { CPageTable, useCPageTable, CPageTableProps } from '@/components/CPageTable';
import { CTableColumn, CTableButtonGroup } from '@/components/CTable';
import type { TableButtonItem } from '@/components/CTable';
import { useTaskList } from './useTaskList';
import { useRouter } from 'vue-router';
import { useKeepAliveRefresh } from '@/hooks/useKeepAliveRefresh';
import { empty } from '@/utils';
import { InventoryTaskListAccountStatusMap, AccountStatusEnum } from '@/constants/enum';
import { hasBtnPermission } from '@/directives/btnPermission';
import { useMessage } from '@/hooks/useMessage';

const router = useRouter();
const { createMessage, createConfirm } = useMessage();
const { searchForm, searchOptions, tableOptions, tableFieldsSetting } = useTaskList();
const options = reactive<CPageTableProps>({
  title: '碳盘查核算',
  searchOptions: searchOptions,
  tableOptions,
  tableFieldsSetting,
  enableFieldsSetting: true
});
const [registerPage, { refresh }] = useCPageTable(options);
useKeepAliveRefresh(refresh);

const addOrEditTaskTaskNo = ref('');
const addOrEditTaskType = ref<'ADD' | 'EDIT'>('ADD');
const addOrEditTaskVisible = ref(false);

// 新建任务
function handleAddTask() {
  addOrEditTaskTaskNo.value = '';
  addOrEditTaskType.value = 'ADD';
  addOrEditTaskVisible.value = true;
}

// 编辑任务
function handleEditTask(row: GetTaskListResult) {
  addOrEditTaskTaskNo.value = row.taskNo;
  addOrEditTaskType.value = 'EDIT';
  addOrEditTaskVisible.value = true;
}

/**
 * 核算按钮
 * @param item 列表item
 */
function handleAccounting(item: GetTaskListResult) {
  router.push(`/inventoryTask/taskList/taskDetail/${item.taskNo}`);
}

function getTaskStatusTagType(accountStatus: keyof typeof AccountStatusEnum) {
  switch (accountStatus) {
    case AccountStatusEnum.ACCOUNTED:
      return 'success';
    case AccountStatusEnum.NOT_ACCOUNT:
      return 'info';
    default:
      return 'info';
  }
}

function handleDelete(row: GetTaskListResult) {
  createConfirm('警告', '会同时删除相关的组织边界的记录，是否继续？', {
    iconType: 'warning'
  }).then(async () => {
    try {
      await postDeleteTask(row.taskNo);
      createMessage.success('删除成功！');
      refresh();
    } catch (error) {
      console.log('error', error);
    }
  });
}

/**
 * 配置表格的按钮
 * @param row 表格行数据
 */
function getTableButtonsConfig(row: GetTaskListResult): TableButtonItem[] {
  return [
    {
      text: '核算',
      btnPermission: 'ECI_INVENTORY_TASK_ACCOUNT',
      onClick: () => handleAccounting(row)
    },
    {
      text: '删除',
      btnPermission: 'ECI_INVENTORY_TASK_DELETE',
      onClick: () => handleDelete(row)
    }
  ];
}
</script>
<style lang="scss">
.inventory-task-list-table-icon {
  color: #96a7b3;
  &:hover {
    color: #03ac82;
  }
}
</style>
